const { HttpRequest, globalData, UserAccess, addUserStat, mfutil } = getApp();
const app = getApp();
Page({
  data: {
    formSubData: {
      fullName: '',
      genderCode: '',
      mobilePhone: '',
      birthDate: ''
    },
    registerActive: false,
    genderCode: '100000002',
    genderCodeIndex: 0,
    mobilePhonewaring: false,
    fullNamewaring: false,
    genderCodewaring: false,
    birthDatewaring: false,
    radio1: false,
    radio2: true,
    Bpopover: false,
    Ppopover: false,
    genderCodeLists: [{ name: '女', value: '100000002', checked: false }, { name: '男', value: '100000001', checked: false }],
    genderCodeRadio: false,
    genderCodeIndex: '100000002',  //性别index
    pickergenderCode: false,
    Ppopovericon: false,
    Bpopovericon: false,
    mobilePhoneFocus: null,
    router: '/pages/index1334/index1334',
    pagetitle: '1334注册页',
    verifyphone: '1',
    loadingActive: false,
    pname: '姓名'
  },
  onLoad() {
    my.hideShareMenu({
      success() {
      },
      fail() {
      },
    });
  },
  async initPage() {
  },
  changeregisterActive(options) {
    let item = ['formSubData.mobilePhone']
    this.setData({
      verifyphone: options.verifyphone,
      [item]: options.mobile
    })
  },
  //  input框记录
  inputRecord(event) {
    let { item } = event.currentTarget.dataset;
    let { value } = event.detail;
    let { mobilePhonewaring } = this.data;


    if (item == 'formSubData.mobilePhone') {
      let reg = /^[0-9]*$/;
      if (!reg.test(value)) {
        mobilePhonewaring = true;
        // value = value.substring(0, value.length - 1);  
        value = value.replace(/[^\d]/g, '')
        console.log('不符合', value)
      } else {
        mobilePhonewaring = false
      }
      this.setData({
        Ppopovericon: false,
        mobilePhonewaring: false,
      })
    }
    let waringItem = item.substring(12) + 'waring';
    this.setData({
      [waringItem]: false,
      [item]: value
    })
  },
  inputRecordgenderCode() {
    my.hideKeyboard();
    this.setData({
      genderCodeRadio: true,
      fullNameFocus: false,
      mobilePhoneFocus: false
    })
  },
  birthDateFn(event) {
    this.setData({
      genderCodeRadio: false,
    })
    let item = 'formSubData.birthDate';
    let time = new Date();
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    my.datePicker({
      format: 'yyyy-MM-dd',
      currentDate: `${y - 16}-${m}-${d}`,
      startDate: '1960-01-01',
      endDate: `${y - 16}-${m}-${d}`,
      success: (res) => {
        let sy = new Date(res.date).getFullYear();
        let sm = new Date(res.date).getMonth() + 1;
        ((sm / 10) < 1) ? sm = `0${sm}` : sm = sm
        let sd = new Date(res.date).getDate();
        ((sd / 10) < 1) ? sd = `0${sd}` : sd = sd
        console.log(Number(sy) > (Number(y) - 16), Number(sm) > Number(m), Number(sd) > Number(d))
        if (Number(sy) > (Number(y) - 16)) {
          my.alert({
            content: '加入会员必须年满16周岁以上'
          })
        }
        this.setData({
          [item]: `${sy}/${sm}/${sd}`,
          Bpopovericon: true,
          birthDatewaring: false
        })
      },
    });
  },
  inputBlur(event) {
    let { item } = event.currentTarget.dataset;
    let { value } = event.detail;
    let { mobilePhonewaring, formSubData } = this.data;

    if (item == 'formSubData.genderCode' && (value !== '100000002' && value !== '100000001')) {
      this.setData({
        genderCodewaring: true
      })
    }
    if (item == 'formSubData.mobilePhone') {
      let reg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
      if (!reg.test(value) && value) {
        mobilePhonewaring = true;
        // value = ''
      } else {
        mobilePhonewaring = false
      }
      this.setData({
        mobilePhonewaring,
        [item]: value,
        Ppopovericon: true,
        mobilePhoneFocus: false,
      })
    }
    if (item == 'formSubData.birthDate') {
      this.setData({
        Bpopovericon: true,
      })
    }
    if (item == 'formSubData.fullName' && formSubData.fullName) {
      this.setData({
        fullNamewaring: false,
      })
    }
  },
  Focus() {
    console.log(this.data.formSubData.fullName.length);

    this.setData({
      genderCodeRadio: false,
    })

  },
  phoneFous() {
    this.setData({
      Ppopovericon: false,
      genderCodeRadio: false
    })
  },
  popoverChange(event) {
    my.hideKeyboard();
    this.setData({
      fullNameFocus: false
    })
    let { item } = event.currentTarget.dataset;
    let current = this.data[item]
    this.setData({
      [item]: !current,
    })
  },
  radioChange(event) {
    let { item } = event.currentTarget.dataset;
    this.setData({
      [item]: !this.data[item]
    })
  },
  /**
   * 性别选择改变
   */
  onChangegenderCode(event) {
    let { genderCodeLists } = this.data;
    this.setData({
      genderCode: genderCodeLists[event.detail.value].value,
      genderCodeIndex: event.detail.value[0],
    })
  },
  successBtn() {
    let item = 'formSubData.genderCode';
    let { genderCode } = this.data;
    this.setData({
      [item]: genderCode,
      genderCodeRadio: false,
      genderCodewaring: false
    })
  },
  failBtn() {
    this.setData({
      genderCodeRadio: false
    })
  },
  /**
   * 提交注册
   */
  async submitFn() {
    let { formSubData, radio1, radio2 } = this.data;
    let currentItem = '';
    // for (var item in formSubData) {
    //   if (formSubData[item] == '') {
    //     currentItem = item + 'waring';
    //     break;
    //   }
    // }
    // if (currentItem !== '') {
    //   this.setData({
    //     [currentItem]: true
    //   })
    // } else {
    if (radio1 && radio2) {
      let path = `/vans-family/api/v2.1/project/vansFamily/clm/forward?url=/v1/member/api/tmall/register`;
      let birthYear = formSubData.birthDate ? new Date(formSubData.birthDate).getFullYear() : '';
      let birthMonth = formSubData.birthDate ? new Date(formSubData.birthDate).getMonth() + 1 : '';
      let birthDay = formSubData.birthDate ? new Date(formSubData.birthDate).getDate() : '';
      let bodyObj = {
        "mobilePhone": formSubData.mobilePhone,
        "source": 100000020,
        "subSource": 100000501,
        "fullName": formSubData.fullName,
        "genderCode": formSubData.genderCode,
        "birthYear": birthYear.toString(),
        "birthMonth": (birthMonth / 10 < 1) ? '0' + birthMonth : birthMonth,
        "birthDay": (birthDay / 10 < 1) ? '0' + birthDay : birthDay,
        "storeCode": "TMALL",
        "thirdType": 1,
        "thirdPartyId": globalData.ouid
      }
      my.confirm({
        title: '温馨提示',
        content: '生日信息提交后不可修改，请谨慎填写',
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        success: async (result) => {
          console.log(result);

          if (result.confirm) {
            my.showLoading({
              content: '注册中···'
            });
            let res = await HttpRequest(path, 'POST', '', bodyObj);
            my.hideLoading({
              page: this,  // 防止执行时已经切换到其它页面，page指向不准确
            });
            if (res.data.resultCode == 0) {
              this.queryMember()
              this.setData({
                verifyphone: '2',
              })
              /**
                * 用户行为记录埋点
                */
              let routerArr = getCurrentPages();
              let options = {
                grade: routerArr.length > 1 ? routerArr[routerArr.length - 2].data.router : '',
                name: routerArr[routerArr.length - 1].data.pagetitle
              }
              let track = UserAccess(options)



              // 自定义埋点
              let customAccessoptions = {
                customType: '注册'
              }
              console.log('注册');

              let tracks = addUserStat(customAccessoptions)

            } else {
              my.alert({
                content: res.data.resultDesc
              })
              // mfutil.launchErrPage(53001)
            }
          }
        },
      });
    } else {
      my.alert({
        content: '请接受协议条款！'
      })
    }
    // }

  },
  async queryMember() {
    // 注册成功后重新拉取会员信息,保存到全局
    //重新获取会员信息
    let memberObj = {
      "param": globalData.ouid,
      "type": 3
    }
    let memberPath = `/vans-family/api/v2.1/project/vansFamily/clm/forward/sendjson/get?url=/v1/member/api/tmall/query`;
    this.setData({
      loadingActive: true
    })
    let memberRes = await HttpRequest(memberPath, 'POST', '', memberObj);
    this.setData({
      loadingActive: false
    })
    if (memberRes.data.resultCode == 0) {
      // memberRes.data.data.fullName = memberRes.data.data.fullName!=''? memberRes.data.data.fullName: '会员';      
      globalData.userInfo = memberRes.data.data;
    } else {
      my.alert({
        content: memberRes.data.resultDesc
      })
      // mfutil.launchErrPage(53001)

    }
  },
  skipFn() {
    my.switchTab({
      url: '/pages/integral-page/integral-page'
    });
  },
  tandcTo() {
    my.navigateTo({
      url: '/pages/tandc/tandc'
    });
  },
  privacyTo() {
    my.navigateTo({
      url: '/pages/privacy-page/privacy-page'
    });
  }
});
